import { useEffect } from "react";

import "./index.scss";

interface ScrollType {
  key: number;
  text: string;
}

export default function ScrollAnimation() {
  const scrollList: ScrollType[] = [
    { key: 1, text: "Content" },
    { key: 2, text: "Content" },
    { key: 3, text: "Content" },
    { key: 4, text: "Content" },
    { key: 5, text: "Content" },
    { key: 6, text: "Content" },
    { key: 7, text: "Content" },
    { key: 8, text: "Content" },
    { key: 9, text: "Content" },
  ];

  const handleScrollPage = () => {
    const domList = document.getElementsByClassName("sa-box");
    const bomHeight = document.body.clientHeight;
    for (let i = 0; i < domList.length; i++) {
      const marTop = domList[i].getBoundingClientRect().top;
      if (marTop < 0 || marTop > bomHeight) {
        if (i % 2 === 0) {
          //@ts-ignore
          domList[i].style.transform = "translateX(1000px)";
        } else {
          //@ts-ignore
          domList[i].style.transform = "translateX(-1000px)";
        }
      } else {
        //@ts-ignore
        domList[i].style.transform = "translateX(0)";
      }
    }
  };

  useEffect(() => {
    handleScrollPage();
  }, []);

  function debounce(func: any, wait: number) {
    let timeout: any;
    return function () {
      //@ts-ignore
      let context = this;
      let args = arguments;

      if (timeout) clearTimeout(timeout);

      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    };
  }

  return (
    <div
      className='scroll-animation'
      onScroll={() => debounce(handleScrollPage(), 100)}
    >
      <span>滚动加载动画</span>
      {scrollList.map((item, index) => (
        <div
          key={item.key}
          className='sa-box'
          style={{
            transform:
              index % 2 === 0 ? "translateX(1000px)" : "translateX(-1000px)",
          }}
        >
          {item.text}
        </div>
      ))}
    </div>
  );
}
